package com.xhsj.user.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * 阿里云短信发送工具栏
 * @author suxiaolin
 * @date 2019/9/24 17:46
 */
@Slf4j
public class AliyunMessage {
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    // accessKeyId，accessKeySecret寻找步骤参考官方文档
    //https://help.aliyun.com/document_detail/55284.html?spm=5176.10629532.106.1.24981cbeej0YCz
    static final String accessKeyId = "LTAI4FrmJLccG45UZfkLSaQb";
    static final String accessKeySecret = "8ffMxEtYnlxwGBuzs3ULZBAJsxEQLb";

    // 方法名可以自行定义
    // 参数可以自己定义随意更改，更改为你自己需要的参数即可
    // 返回值类型可以自行定义
    public static Message sendSms(String phone,String moudleName,String name) {

        try {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号
            request.setPhoneNumbers(phone);

            //必填:短信签名-可在短信控制台中找到
            request.setSignName("芯海视界OA系统");
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode("SMS_220370060");
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//            String random = random();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("module", moudleName);
            jsonObject.put("name", name);
            request.setTemplateParam(JSON.toJSONString(jsonObject));
            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");

            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("yourOutId");

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                log.info("短信发送成功,手机号:{},模块名:{},发送人:{}",phone,moudleName,name);
                return Message.success();
            }else{
                log.error("短信发送失败,请稍后重试");
                return Message.error(1,sendSmsResponse.getMessage());
            }
        } catch (com.aliyuncs.exceptions.ClientException e) {
            log.error("验证码发送失败,请稍后重试",e);
            return Message.error(1,e.getMessage());
        }
    }


    public static Message sendValidateCode(String phone) {

        try {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号
            request.setPhoneNumbers(phone);

            //必填:短信签名-可在短信控制台中找到
            request.setSignName("芯海视界OA系统");
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode("SMS_174875837");
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            String random = random();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", random);
            request.setTemplateParam(JSON.toJSONString(jsonObject));
            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");

            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("yourOutId");

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                System.err.println("发送成功,验证码："+random);
                return Message.success("成功",random);
            }else{
                return Message.error(1,"验证码发送失败,请稍后重试"+sendSmsResponse.getMessage());
            }
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
            return Message.error(1,"验证码发送失败,请稍后重试"+e.getMessage());
        }
    }

    public static void main(String[] args) {
//        sendSms("18911423130");
        sendSms("15311766807","请假管理","苏小林");
    }

    public static String random(){
        String sources = "0123456789"; // 加上一些字母，就可以生成pc站的验证码了
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++)
        {
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }
        System.out.println(flag.toString());
        return flag.toString();
    }

}
